<script setup>
import { ref, reactive } from 'vue'
import request from '@/utils/request'

import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

const myform = ref(null)
const input = ref(null)
const form = reactive({
    username: '',
    password: '',
    nickname: '',
    phone: ''
})

const rules = {
    username: [
        { required: true, message: '请填写用户名' }
    ],
    password: [
        { required: true, message: '请填写密码' },
        { min: 3, max: 20, mwssage: '密码长度必须3到20个字之间', trigger: 'blur' }
    ]
}

const onSubmit = function () {
    myform.value.validate(async function (valid) {
        if (!valid) return

        const  {data}  = await request.post('/user/add', {
               ...form
        })
        if (data.code === 200) {
            ElMessage.success('添加用户成功')
            
            router.push('list')
        }
    })

}
</script>

<template>
    <div>
        <h4>添加用户</h4>
        <el-row :gutter="20">
            <el-col :span="16">
                <el-form :model="form" :rules="rules" label-width="120px" ref="myform">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="form.username" ref="input" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" show-password v-model="form.password"/>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname" >
                        <el-input v-model="form.nickname" />
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phone">
                        <el-input v-model="form.phone" >
                            <template #prepend>+86</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">添加</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>
